import axios from "axios";
import { Service } from "typedi";
import { LOGIN_DOMAIN } from "config/config";
import { RES_INFO, REPO_TOKEN } from "config/const";

export const HTTP_LOGIN_INTERFACE = "httpLoginInterface";

export interface tokenEntity {
  [key: string]: any;
}

export interface httpLoginInterface {
  getToken(code: string): Promise<tokenEntity>;
  getUserInfo(access_token: string): Promise<tokenEntity>;
  getUserInfoById(opts: any): Promise<tokenEntity>;
}

@Service(HTTP_LOGIN_INTERFACE)
class repo implements httpLoginInterface {
  // 获取token
  async getToken(code: string): Promise<tokenEntity> {
    return new Promise<any>(async (resolve, reject) => {
      const url = `${LOGIN_DOMAIN}/oauth2/token`;
      try {
        const res: any = await axios({ url, method: "GET", params: { code } });
        // 该接口成功不会返回no字段 除非报错
        if (res.no == 1 || !res.data.access_token) {
          resolve(REPO_TOKEN(`获取oauth2的token失败：${res}`, "获取token"));
        } else {
          resolve(RES_INFO({ data: res.data }));
        }
      } catch (e) {
        resolve(REPO_TOKEN(`获取oauth2的token失败：${e}`, "获取token"));
      }
    });
  }

  // 通过token获取用户信息
  async getUserInfo(access_token: string): Promise<tokenEntity> {
    return new Promise<any>(async (resolve, reject) => {
      const url = `${LOGIN_DOMAIN}/oauth2/userinfo`;
      try {
        const res: any = await axios({
          url,
          method: "GET",
          params: { access_token },
        });
        if (res.data.no != 0) {
          resolve(
            REPO_TOKEN(`获取用户信息失败：${res}`, "通过token获取用户信息")
          );
        } else {
          const info = res.data.data || {};
          info.oauth2Token = access_token;
          resolve(RES_INFO({ data: info }));
        }
      } catch (e) {
        resolve(REPO_TOKEN(`获取用户信息失败：${e}`, "通过token获取用户信息"));
      }
    });
  }

  // 通过id获取用户信息
  async getUserInfoById(opts: any): Promise<tokenEntity> {
    const { userInfo, request, response } = opts;
    return this.getUserInfo(userInfo.oauth2Token);
  }
}
